package com.gcpproxy.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class ChatMessage {
    
    private String role;
    
    private Object content; // 可以是 String 或 List<ContentItem>
    
    @JsonProperty("content")
    public void setContent(Object content) {
        if (content instanceof List) {
            ObjectMapper mapper = new ObjectMapper();
            List<ContentItem> items = new ArrayList<>();
            for (Object item : (List<?>) content) {
                if (item instanceof ContentItem) {
                    items.add((ContentItem) item);
                } else {
                    items.add(mapper.convertValue(item, ContentItem.class));
                }
            }
            this.content = items;
        } else {
            this.content = content;
        }
    }
    
    @SuppressWarnings("unchecked")
    public List<ContentItem> getContentItems() {
        if (content instanceof List) {
            return (List<ContentItem>) content;
        }
        return null;
    }
    
    public String getTextContent() {
        if (content instanceof String) {
            return (String) content;
        }
        List<ContentItem> items = getContentItems();
        if (items != null) {
            StringBuilder text = new StringBuilder();
            for (ContentItem item : items) {
                if (item != null && item.isText() && item.getText() != null) {
                    text.append(item.getText()).append("\n");
                }
            }
            return text.toString();
        }
        return "";
    }
    
    public List<String> getImageUrls() {
        List<ContentItem> items = getContentItems();
        if (items != null) {
            return items.stream()
                    .filter(item -> item != null && item.isImage() && item.getImageUrl() != null && item.getImageUrl().getUrl() != null)
                    .map(item -> item.getImageUrl().getUrl())
                    .toList();
        }
        return List.of();
    }
}